import {
  Controller,
  Post,
  UseInterceptors,
  UploadedFile,
  UploadedFiles,
  Query,
  Get,
  Param,
  Res,
} from '@nestjs/common';
import { FileInterceptor, FilesInterceptor } from '@nestjs/platform-express';
import type { Response } from 'express';

import { StorageService } from './storage.service';
import type { BufferedFile } from 'src/types';

@Controller('storage')
export class StorageController {
  constructor(private readonly storageService: StorageService) {}

  @Post('/file')
  @UseInterceptors(FileInterceptor('file'))
  uploadFile(@UploadedFile('file') file: BufferedFile) {
    return this.storageService.uploadFile(file);
  }

  @Post('files')
  @UseInterceptors(FilesInterceptor('files'))
  uploadFiles(@UploadedFiles() files: Array<BufferedFile>) {
    return this.storageService.uploadFiles(files);
  }

  @Get('/download')
  async downloadFile(@Query('id') id: string, @Res() res: Response) {
    const { file, stream } = await this.storageService.downloadFile(id);

    res.set({
      'Content-Type': 'application/octet-stream',
      'Content-Disposition': `attachment; filename="${encodeURIComponent(file.name)}"`,
    });

    // 将 MinIO 的流直接 pipe 到响应
    stream.pipe(res);
  }

  @Get()
  findAll(@Query('current') current: number, @Query('pageSize') pageSize: number) {
    return this.storageService.findAll(Number(current), Number(pageSize));
  }

  @Get(':id')
  findOne(@Param('id') id: string) {
    return this.storageService.findOne(id);
  }
}
